package com.example.flowable.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.example.annotations.*;
import com.example.db.model.IPage;
import com.example.flowable.model.FlowableModel;
import com.example.flowable.model.TableModel;
import com.example.flowable.model.TableModelConfig;
import com.example.flowable.model.enummodel.TableFieldTypeEnum;
import com.example.flowable.model.vo.TableModelVo;
import com.example.flowable.service.FlowableModelService;
import com.example.flowable.service.TableModelService;
import com.example.flowable.utils.FormModelUtils;
import com.example.utils.Results;
import com.example.utils.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname TableModelController
 * @Description TODO
 * @Date 2022/8/17 9:21
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Auth
@RestController("/tablemodel")
public class TableModelController {

    @Autowired
    private TableModelService tableModelService;

    @Autowired
    private FlowableModelService flowableModelService;


    @PostMapping(value = "/page",desc = "数据表分页")
    public JSONObject pageController(@Param(value = "pageNum",desc = "页码",defalultValue = "1")Integer pageNum,
                                     @Param(value = "pageSize",desc = "条数",defalultValue = "10")Integer pageSize,
                                     @Param(value = "searchParams",required = false)JSONObject object){
        IPage<TableModel> iPage=tableModelService.page(pageNum, pageSize, object);
        return Results.successLayuiTable(iPage);
    }

    @PostMapping(value = "/save",desc = "数据建表")
    public JSONObject saveController(@RequestBody TableModelVo tableModelVo){
        if(tableModelVo.getTableName()==null){
            return Results.error("表名不得为空");
        }
        if(tableModelVo.getName()==null){
            return Results.error("模型名称不得为空");
        }
        if(tableModelVo.getDescNote()==null){
            return Results.error("模型描述不得为空");
        }
        if(tableModelVo.getTableModelConfigs()==null || tableModelVo.getTableModelConfigs().isEmpty()){
            return Results.error("模型字段属性不得为空");
        }
        TableModel tableModel=tableModelService.getTableModelByTableName(tableModelVo.getTableName());
        if(tableModel!=null){
            return Results.success(tableModelVo.getTableName()+" 表名已存在");
        }
        tableModelService.createTable(tableModelVo);
        TableModel model=new TableModel();
        model.setTableName(tableModelVo.getTableName());
        model.setName(tableModelVo.getName());
        model.setDescNote(tableModelVo.getDescNote());
        model.setCreatedate(new Date());
        model.setTableConfig(JSONArray.toJSONString(tableModelVo.getTableModelConfigs()));
        List<String> fields=tableModelVo.getTableModelConfigs().stream().map(e->e.getFieldName()).collect(Collectors.toList());
        model.setTableField(JSONArray.toJSONString(fields));
        tableModelService.save(model);
        return Results.success("新增成功");
    }

    @GetMapping(value = "/getfieldtype",desc = "获取字段类型")
    public JSONObject getFiledTypeController(){
        JSONArray array=new JSONArray();
        TableFieldTypeEnum[] fields=TableFieldTypeEnum.values();
        JSONObject object=null;
        for (int i = 0; i < fields.length; i++) {
            object=new JSONObject();
            TableFieldTypeEnum tableFieldTypeEnum=fields[i];
            object.put("fieldType",tableFieldTypeEnum.getFieldType());
            object.put("name",tableFieldTypeEnum.getName());
            object.put("fieldLength",tableFieldTypeEnum.getFieldLength());
            object.put("isPoint",tableFieldTypeEnum.isPoint());
            array.add(object);
        }
        return Results.success(array);
    }

    @GetMapping(value = "/getformconfig",desc = "获取表单配置")
    public JSONObject getFormConfigController(@Param("id")String id){
        TableModel tableModel=tableModelService.getById(id);
        if(tableModel == null){
            return Results.error("系统错误");
        }
        List<TableModelConfig> tableModelConfigs=JSONArray.parseArray(tableModel.getTableConfig(),
                TableModelConfig.class);
        if(!tableModel.isIsform()){
            JSONArray array= FormModelUtils.getFormModelArray(tableModelConfigs);
            return Results.success(array);
        }
        JSONArray array=JSONArray.parseArray(tableModel.getFormconfig());
        return Results.success(array);
    }

    @PostMapping(value = "/saveTableModelConfig",desc = "表单配置存储")
    public JSONObject saveTableModelConfigController(@RequestBody JSONObject object){
        if(object.get("id")==null){
            return Results.error("id不得为空");
        }
        Object id=object.get("id");
        TableModel tableModel=tableModelService.getById(id);
        if(tableModel == null){
            return Results.error("请检查系统配置后在重试");
        }
        String html=object.getString("html");
        JSONArray fields=object.getJSONArray("fields");
        tableModel.setIsform(true);
        tableModel.setFormconfig(fields.toJSONString());
        tableModel.setFormhtml(html);
        tableModelService.updateById(tableModel);
        return Results.success("成功");
    }

    @PostMapping(value = "/getData",desc = "获取数据")
    public JSONObject getDataController(@Param(value = "dataId",desc = "数据id")Integer dataId,
                                        @Param(value = "processModelId",desc = "流程模型id")Integer processModelId){
        FlowableModel flowableModel=flowableModelService.getById(processModelId);
        if(flowableModel==null){
            return Results.error("流程模型不存在");
        }
        if(flowableModel.getFromId()==null){
            return Results.error("流程未配置表单");
        }
        TableModel tableModel=tableModelService.getById(flowableModel.getFromId());
        if(tableModel == null){
            return Results.error("表单模型不存在");
        }
        Map<String,Object> map=tableModelService.getData(tableModel.getTableName(),dataId);
        return Results.success(map);
    }

    @PostMapping("/saveData")
    public JSONObject saveDataController(@RequestBody JSONObject object){
        if(object==null){
            return Results.error("数据不得为空");
        }
        Object tableName=object.get("tableName");
        if(StringUtils.isEmpty(tableName)){
            return Results.error("数据表不得为空");
        }
        Object data=object.get("data");
        if(StringUtils.isEmpty(data)){
            return Results.error("数据不得为空");
        }
        Object id=object.get("id");
        String processTitle=object.getString("processTitle");
        String processModelId=object.getString("processModelId");
        String processdefid=object.getString("processdefid");
        if(!StringUtils.isEmpty(id)){
            //更新
            Map<String,Object> obj=(Map<String, Object>) data;
            obj.put("processTitle",processTitle);
            obj.put("processModelId",processModelId);
            obj.put("processdefid",processdefid);
            obj.put("id",id);
            tableModelService.updateDataById(String.valueOf(tableName),obj);
        }else {
            Map<String,Object> obj=(Map<String, Object>) data;
            obj.put("processTitle",processTitle);
            obj.put("processModelId",processModelId);
            obj.put("processdefid",processdefid);
            //保存
            Integer dataId=tableModelService.saveData(String.valueOf(tableName),obj);
            object.put("id",dataId);
        }
        return Results.success(object);
    }

//    @PostMapping(value = "/saveTableModel",desc = "新建表模型")
//    public JSONObject saveTableModelController(@Param("tableName")String tableName,
//                                               @Param("name")String name,
//                                               @Param("descNote")String descNote){
//        TableModel tableModel =new TableModel();
//        tableModel.setDescNote(descNote);
//        tableModel.setTableName(tableName);
//        tableModel.setName(name);
//        tableModel.setCreatedate(new Date());
//        tableModelService.save(tableModel);
//        return Results.success(tableModel);
//    }
}
